package com.gsnd.gsnd22estore.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.domain.OrderItem;
import com.gsnd.gsnd22estore.domain.EsOrder;
import com.gsnd.gsnd22estore.domain.EsOrderItem;
import com.gsnd.gsnd22estore.domain.EsShopcar;
import com.gsnd.gsnd22estore.dto.CreateOrderDTO;
import com.gsnd.gsnd22estore.dto.OrderItemsDTO;
import com.gsnd.gsnd22estore.dto.OrderPaySuccessDTO;
import com.gsnd.gsnd22estore.dto.QueryOrderDTO;
import com.gsnd.gsnd22estore.dto.extend.QueryOrderDTOExtend;
import com.gsnd.gsnd22estore.exception.BookStoreException;
import com.gsnd.gsnd22estore.mapper.EsBookMapper;
import com.gsnd.gsnd22estore.mapper.EsOrderItemMapper;
import com.gsnd.gsnd22estore.mapper.EsOrderMapper;
import com.gsnd.gsnd22estore.mapper.EsShopcarMapper;
import com.gsnd.gsnd22estore.service.OrderService;
import com.gsnd.gsnd22estore.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    EsOrderMapper orderMapper;
    @Autowired
    EsShopcarMapper shopCarMapper;
    @Autowired
    EsBookMapper bookMapper;
    @Autowired
    EsOrderItemMapper orderItemMapper;

    @Override
    public List<QueryOrderDTO> getOrderByUser(Integer userId, Integer status, String orderId) {
        List<QueryOrderDTO> queryOrderDTOS = orderMapper.selectByCondition(userId, orderId, status);

        // 推荐使用数学计算
        for(QueryOrderDTO o: queryOrderDTOS){
            // 准备两个变量进行接收
            int numSum = 0;
            double priceSum = 0.0;
            List<OrderItemsDTO> orderItemsDTOS = orderMapper.selectItemByOrderId(o.getOrderId());
            for(OrderItemsDTO oi : orderItemsDTOS){
                numSum += oi.getNum();
                priceSum += oi.getTotalPrice();
            }
            o.setTotalNum(numSum);
            o.setTotalPrice(priceSum);
        }
        System.out.println(queryOrderDTOS);
        return queryOrderDTOS;
    }

    @Override
    public QueryOrderDTOExtend getOrderDetailByUser(Integer userId, String orderId) {
        List<QueryOrderDTO> queryOrderDTOS = orderMapper.selectByCondition(userId, orderId, null);
        // 取出查询的订单对象
        QueryOrderDTO queryOrderDTO = queryOrderDTOS.get(0);
        // 复制bean对象
        QueryOrderDTOExtend oe = BeanCopyUtils.copyBean(queryOrderDTO, QueryOrderDTOExtend.class);
        // 根据oe查询订单项
        List<OrderItemsDTO> orderItemsDTOS = orderMapper.selectItemByOrderId(oe.getOrderId());
        oe.setOrderItems(orderItemsDTOS);

        return oe;
    }

    @Override
    public QueryOrderDTOExtend addOrder(CreateOrderDTO createOrderDTO, Integer userId) {
        // 通过购物车内容id，获取所有商品信息
        List<Integer> shopCarIds = createOrderDTO.getShopCarIds();
        List<EsShopcar> esShopcars = shopCarMapper.selectList(shopCarIds);

        // 创建订单对象
        EsOrder order = new EsOrder();
        // 唯一id生成策略，使用最简单的uuid
        order.setId("briup"+IdUtil.simpleUUID());
        order.setUserId(userId);
        order.setCreateDate(LocalDate.now());
        order.setStatus(1);
        order.setReceiveAddress(createOrderDTO.getReceiveAddress());
        order.setReceivePhone(createOrderDTO.getReceivePhone());
        order.setReceiveUsername(createOrderDTO.getReceiveUsername());

        orderMapper.insert(order);

        // 创建订单项对象
        // 删除购物车选项
        shopCarIds.forEach(i->{
            EsShopcar shopcar = shopCarMapper.findById(i);
            EsOrderItem item = BeanCopyUtils.copyBean(shopcar, EsOrderItem.class);
            item.setOrderId(order.getId());
            orderItemMapper.insert(item);
            shopCarMapper.deleteById(i);
            bookMapper.updateStoreNumById(Math.negateExact(item.getNum()),item.getBookId());
        });

        return getOrderDetailByUser(userId,order.getId());
    }

    @Override
    public void closeOrder(String id) {
        // 判断当前订单状态是否是已下单未支付
        EsOrder order = orderMapper.selectOrderById(id);
        if (order.getStatus() != 1) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.ORDER_CAN_NOT_CLOSE);
        }
        // 关闭该订单
        orderMapper.updateStatusToClose(id);
        List<EsOrderItem> list = orderItemMapper.findByOrderId(id);
        for (EsOrderItem item : list) {
            bookMapper.updateStoreNumById(item.getNum(),item.getBookId());

        }
    }

    @Override
    public void paySuccess(OrderPaySuccessDTO paySuccessDTO) {
        orderMapper.paySuccess(paySuccessDTO);
    }

    @Override
    public void completeOrder(String orderId) {
        EsOrder order = orderMapper.selectOrderById(orderId);
        if (order.getStatus() != 3) {
            throw new BookStoreException(BookStoreException.CodeMsgEnum.ORDER_CAN_NOT_COMPLETE);

        }
        orderMapper.completeOrder(orderId);
    }
}
